#include "databasedialog.h"
#include "ui_databasedialog.h"
#include "dbtablemodel.h"
#include "dbcolumnsmodel.h"
#include "combodelegate.h"
#include "abstractstorage.h"
#include "abstractcontainer.h"
#include "designerworkbench.h"
#include "project.h"
#include "defines.h"
#include "customitemeditor.h"

#include <QMessageBox>
#include <QItemSelectionModel>
#include <QModelIndex>

DatabaseDialog::DatabaseDialog(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::DatabaseDialog),
    m_workbench(QDesignerWorkbench::instance())
{
    m_TablesModel = new DbTableModel(this);
    m_TablesModel->setObjectName(XML_TABLE);
    m_ColumnsModel = new DbColumnsModel(this);
    m_ColumnsModel->setObjectName(XML_COLUMN);


    ui->setupUi(this);

    AbstractContainer *databases = m_workbench->project()->databases();

    for(int i=0; i<databases->size(); i++) {
        m_databases.append( databases->at(i) );
    }

    this->setWindowFlags(this->windowFlags() & ~Qt::WindowContextHelpButtonHint);

    ui->tablesView->setModel(m_TablesModel);
    ui->tablesView->setSelectionBehavior(QAbstractItemView::SelectRows);
    ui->tablesView->setSelectionMode(QAbstractItemView::SingleSelection);
    ui->columnsView->setModel(m_ColumnsModel);
    ui->columnsView->setSelectionBehavior(QAbstractItemView::SelectRows);
    ui->columnsView->setSelectionMode(QAbstractItemView::SingleSelection);

    CustomItemEditor *editor = new CustomItemEditor(this);
    ui->columnsView->setItemDelegate(editor);

    connect( ui->tablesView->selectionModel(), SIGNAL(currentRowChanged(QModelIndex,QModelIndex)),this, SLOT(tableListRowChanged(QModelIndex,QModelIndex)) );
    populateDatabaseList();
}

DatabaseDialog::~DatabaseDialog()
{
    delete ui;
}

void DatabaseDialog::on_addButton_clicked()
{        
    int row = ui->dbTableWidget->rowCount();
    QString dbName = "database"+QString::number(row+1);
    QString conStr = "/mnt/sdcard";

    AbstractStorage* database = m_databases.appendStorage(XML_DATABASE);
    database->setProperty(PROP_DATABASENAME, dbName);
    database->setProperty(PROP_CONNECTIONSTRING, conStr);

    ui->dbTableWidget->insertRow(row);
    ui->dbTableWidget->setItem(row, 0, new QTableWidgetItem(dbName));
    ui->dbTableWidget->setItem(row, 1, new QTableWidgetItem("/mnt/sdcard"));
    ui->dbTableWidget->setCurrentCell(row, 0);
}

void DatabaseDialog::on_removeButton_clicked()
{   
    int row = ui->dbTableWidget->currentRow();
    if (row >= 0 ){
        ui->dbTableWidget->removeRow(row);
        m_databases.removeAt(row);
    }
    if (ui->dbTableWidget->currentRow()== -1){
        m_TablesModel->setTablesList(0);
        m_ColumnsModel->setColumnsList(0);
    }
}

void DatabaseDialog::done(int res)
{
    if(res == QDialog::Accepted) {
        AbstractContainer *databases = m_workbench->project()->databases();
        databases->clear();
        for(int i = 0; i < m_databases.size(); i++ ) {
            AbstractStorage *db = m_databases.at(i);
            db->setProperty(PROP_DATABASENAME, ui->dbTableWidget->item(i,0)->text());
            db->setProperty(PROP_CONNECTIONSTRING, ui->dbTableWidget->item(i,1)->text());
            databases->append( m_databases.at(i) );
        }
    }

    QDialog::done(res);
}

void DatabaseDialog::populateDatabaseList()
{
    while(ui->dbTableWidget->rowCount()>0)
        ui->dbTableWidget->removeRow(0);

    for( int i = 0; i<m_databases.size(); i++ ) {
        int row = ui->dbTableWidget->rowCount();
        ui->dbTableWidget->insertRow(row);
        ui->dbTableWidget->setItem(row, 0, new QTableWidgetItem(m_databases.at(i)->property(PROP_DATABASENAME).toString()));
        ui->dbTableWidget->setItem(row, 1, new QTableWidgetItem(m_databases.at(i)->property(PROP_CONNECTIONSTRING).toString()));
    }
    if( m_databases.size()==1 )
        ui->dbTableWidget->setCurrentCell(0, 0);
}

void DatabaseDialog::tableListRowChanged(QModelIndex current, QModelIndex )
{
    AbstractStorage *database = m_databases.at( ui->dbTableWidget->currentRow() );
    AbstractContainer *tables = database->containerByName(XML_TABLES);
    if( tables && current.row() >= 0 ) {
        AbstractStorage *table = tables->at( current.row() );
        AbstractContainer *columns = table->containerByName( XML_COLUMNS );
        if( columns )
            m_ColumnsModel->setColumnsList(columns);
    }
}
void DatabaseDialog::on_addTable_clicked()
{
    int row = ui->dbTableWidget->currentRow();
    if(row>=0)
        m_TablesModel->insertRow( m_TablesModel->rowCount() );
    else
        QMessageBox::information(this,"Can't create table","Select database first!");
}

void DatabaseDialog::on_removeTable_clicked()
{
    int row = ui->tablesView->currentIndex().row();
    if( row>=0 ) {
        m_ColumnsModel->setColumnsList(0);
        m_TablesModel->removeRow(row);
    }
}

void DatabaseDialog::on_addColumn_clicked()
{
    int row = ui->tablesView->currentIndex().row();
    if( row>= 0 )
        m_ColumnsModel->insertRow( m_ColumnsModel->rowCount() );
    else
        QMessageBox::information(this,"Can't append column","Select table first!");
}


void DatabaseDialog::on_removeColumn_clicked()
{
    int row = ui->columnsView->currentIndex().row();
    if( row>=0 )
        m_ColumnsModel->removeRow(row);
}

void DatabaseDialog::on_dbTableWidget_currentCellChanged(int currentRow, int /*currentColumn*/, int /*previousRow*/, int /*previousColumn*/)
{
    if (currentRow >=0 ) {
        AbstractStorage *database = m_databases.at(currentRow);
        AbstractContainer *tables = database->containerByName(XML_TABLES);
        if( tables ){
            m_TablesModel->setTablesList(tables);
        }
    m_ColumnsModel->setColumnsList(0);
    }
}
